<?php

require_once ('configs/Config.php');
require_once ('BaseController.php');
class ErrorController extends BaseController {
	
	public function errorAction() {
		$errors = $this->_getParam ( 'error_handler' );
		if ($errors == null || ! $errors instanceof ArrayObject) {
			//maybe the user is trying to access this page directly?
			$this->returnToHomepage ();
			return;
		}
		
		switch ($errors->type) {
			case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER :
			case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE :
			case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION :
				// 404 error -- controller or action not found
				$this->getResponse ()->setHttpResponseCode ( 404 );
				$this->view->message = 'Page not found';
				$this->_forward ( 'not-found' );
				break;
			case ExceptionConfig::PERM_EXCEPTION :
				$this->getResponse ()->setHttpResponseCode ( 403 );
				$this->view->message = 'Access denied';
				$this->view->information = $errors->exception->getMessage ();
				$this->_forward ( 'perm-denied' );
				break;
			case ExceptionConfig::UNDERMAINTENANCE_EXCEPTION :
				$this->getResponse ()->setHttpResponseCode ( 410 );
				$this->view->message = 'Under Maintenance';
				$this->view->information = $errors->exception->getMessage ();
				$this->_forward ( 'under-maintenance' );
				break;
			default :
				// application error
				$this->getResponse ()->setHttpResponseCode ( 500 );
				$this->view->message = 'Application error';
				break;
		}
		
		// Log exception, if logger available
		$log = $this->getLog ();
		
		if ($log != false)	{
			$log->crit ( $this->view->message, $errors->exception );
		}
		
		// conditionally display exceptions
		if (GlobalConfig::$verbose) {
			$this->view->exception = $errors->exception;
			$this->view->showStackTrace = GlobalConfig::$showStackTrace;
		}
		
		$this->view->request = $errors->request;
	}
	
	public function getLog() {
		$bootstrap = $this->getInvokeArg ( 'bootstrap' );
		if (! $bootstrap->hasPluginResource ( 'Log' )) {
			return false;
		}
		$log = $bootstrap->getResource ( 'Log' );
		return $log;
	}
	
	public function permDeniedAction() {
	
	}
	
	public function notFoundAction() {
		$this->view->response = Message::ERROR_NOTFOUND;
	}
	
	public function underMaintenanceAction() {
		$this->view->response = Message::ERROR_SERVER_DOWN;
	}

}

